﻿using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Windows.Forms;

namespace CustomizeControl
{
    public class ParallelogramButton : Button
    {
        private int skewOffset = 25;

        public ParallelogramButton()
        {
            SetStyle(ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.ResizeRedraw |
                     ControlStyles.UserPaint, true);

            this.FlatStyle = FlatStyle.Flat;
            this.FlatAppearance.BorderSize = 1;
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;


            // 创建平行四边形路径
            using (GraphicsPath path = new GraphicsPath())
            using (SolidBrush brush = new SolidBrush(this.BackColor))
            {
                Point[] points = CalculatePoints();
                path.AddPolygon(points);

                // 设置点击区域
                this.Region = new Region(path);

                // 绘制背景
                pevent.Graphics.FillPath(brush, path);
            }

            using (var format = new StringFormat())
            {
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;

                // 计算文字绘制区域（留出倾斜空间）
                Rectangle textRect = new Rectangle(
                    skewOffset / 2,
                    0,
                    this.Width - skewOffset,
                    this.Height
                );

                pevent.Graphics.DrawString(this.Text, this.Font,
                            new SolidBrush(this.ForeColor),
                            textRect, format);
            }
        }

        private Point[] CalculatePoints()
        {
            return new Point[]
            {
            new Point(skewOffset, 0),
            new Point(this.Width, 0),
            new Point(this.Width - skewOffset, this.Height),
            new Point(0, this.Height)
            };
        }
    }
}
